/** This class represents the client listener thread 
 *  @author Copyright (c) 2004-2007 by chrmac@gmx.de */

package com.jtalker.client;

import java.io.BufferedReader;

public class JTalkerClientThread extends Thread {
	private BufferedReader in;
	private JTalkerClient theClient;
	private String lastPackage;
	boolean hasNewPackage = false;
	boolean stopNow = false;

	// ArrayList packQueue = new ArrayList();

	public JTalkerClientThread(JTalkerClient client, BufferedReader in) {
		this.theClient = client;
		this.in = in;
	}

	public String getLastPackage() {
		return this.lastPackage;
	}

	public void terminate() {
		this.stopNow = true;
	}

	public void run() {

		try {
			while ((this.lastPackage = in.readLine()) != null) {
				System.out.println("[recv]: " + this.lastPackage);
				if (stopNow){
					return;
				}
				try {
					if (!this.theClient.myProtocol
							.processServerPackage(this.lastPackage)) {
						System.err
								.println("*** Thread: Faulty package recieved: "
										+ this.lastPackage);
					}
				} catch (Exception e) {
					System.err
							.println("*** Thread: Exception occured while parsing server package: "
									+ e.getMessage());
				}
			}
		} catch (Exception e) {
			System.err
					.println("*** Thread: Main-Loop-Error: " + e.getMessage());
		}

		// Notify end of thread
		System.err.println("*** Thread: END: ");

		if (!this.stopNow){
			this.theClient.mainLoopError();
		}
	}
}
